package com.xrit.sunnyday.controller;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.constant.MessageConstant;
import com.xrit.sunnyday.constant.RedisMessageConstant;
import com.xrit.sunnyday.entity.Result;
import com.xrit.sunnyday.pojo.Order;
import com.xrit.sunnyday.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @author Daoying
 * creationTime: 2022/11/19 18:30
 */
@RequestMapping("/order")
@RestController
public class OrderMobileController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;

    /*
     * 提交预约
     * */
    @PostMapping("/submit")
    public Result submit(@RequestBody Map<String, String> paraMap) {
        // 验证码校验
        Jedis jedis = jedisPool.getResource();
        // 手机号码
        String telephone = paraMap.get("telephone");
        // 验证码的 key
        String key = RedisMessageConstant.SENDTYPE_ORDER + "_" + telephone;
        // redis中的验证码
        String codeInRedis = jedis.get(key);
        if (StringUtils.isEmpty(codeInRedis)) {
            //没值 重新发送
            return new Result(false, "请重新获取验证码!");
        }
        // 前端传的验证码
        String validateCode = paraMap.get("validateCode");
        if (!codeInRedis.equals(validateCode)) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        // 移除redis中的验证码，防止重复提交，
        //jedis.del(key);// 测试时可注释掉
        // 设置预约的类型
        //(注意：别在Service层写死，因为Service以后可能还有别的预约需要调用,该模块是移动端，可以写死微信预约)
        paraMap.put("orderType", Order.ORDERTYPE_WEIXIN);
        // 预约成功页面展示时需要用到id
        Order order = orderService.submitOrder(paraMap);
        return new Result(true, MessageConstant.ORDER_SUCCESS, order);
    }


    /*
     * 通过id查询订单
     * */
    @GetMapping("/findById")
    public Result findById(int id) {
        Map orderInfo = orderService.findById(id);
        return new Result(true, MessageConstant.ORDER_SUCCESS, orderInfo);
    }
}
